#-*- coding: utf-8 -*-
import sys
import socket
import threading

class Udpserver(object):
    def __init__(self, _port):
        self.host = ''
        self.port = _port
        self.server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        self.broadCastIp = self.get_host_ip()[:self.get_host_ip().rfind('.')]+'.255'
        self.onlineIp = {}

    # UPD下发送消息,检查设备是否在线
    def initConnect(self, _initCmd, _during, _timeout):
        self._isListen = True
        Udpserver.brodaCastMessage(_initCmd, self.port)
        timer = threading.Timer(_during, self.stopListen)
        timer.start()
        while self._isListen:
            try:
                print self.recMessage(_timeout)
            except Exception,e:
                str(e)

    def stopListen(self):
        self._isListen = False

    # UDP发送消息
    def sendMessage(self, _distIp, _cmd):
        self.host = _distIp
        ADDR = (self.host, self.port)
        self.server.connect(ADDR)  
        self.server.sendto(_cmd.encode('utf-8'), ADDR)
        return True

    @staticmethod
    def brodaCastMessage(_cmd, _port):
        brodaCastSc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        brodaCastSc.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        host_ip = Udpserver.get_host_ip()
        host_broad_ip = host_ip[:host_ip.rfind('.')]+'.255'
        print host_broad_ip
        ADDR = (host_broad_ip, _port) 
        brodaCastSc.sendto(_cmd, ADDR)

    # UPD接受消息
    def recMessage(self, _timeout):
        self.server.settimeout(_timeout)
        ADDR = ('', self.port)
        self.server.bind(ADDR)
        recvData = self.server.recvfrom(1024)
        content, destInfo = recvData
        print 'online device:',content, destInfo
        self.onlineIp.add(destInfo)
        return destInfo,content.decode("utf-8") 

    @staticmethod
    def get_host_ip():
        # try:
        #     self.server.connect(('8.8.8.8', 80))
        #     ip = self.server.getsockname()[0]
        # except Exception,e:
        #     e.message
        ip = socket.gethostbyname(socket.gethostname())
        return ip

     
    def serverClose(self):
        self.server.close()

    def getBroadCastIp(self):
        return self.broadCastIp

if __name__ == "__main__":
    udpserver = Udpserver(2553)
    udpserver.initConnect('FFFF',4,1)
